package com.gxa.meiye.portal.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import com.gxa.meiye.core.utils.RestUtils;
import com.gxa.meiye.portal.hread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: zy
 * @CreateTime: 2022-07-07  15:39
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    RestTemplate restTemplate=null;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头获取token
        String token = request.getHeader("token");
        String method = request.getMethod();
        System.out.println(method);
        //判断token是否存在
        if (StringUtils.isEmpty(token)){
            throw  new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }
//        //发起向远程sso的调用
        String url="http://localhost:8082/consumer/check";
//        //请求头（包括请求类型）
//        HttpHeaders httpHeaders=new HttpHeaders();
//        //指定参数类型对应java中的@RequestParam
//        //MediaType.APPLICATION_JSON对应@Reqestbody
//        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        //传自定义的请求头
//        //httpHeaders.set("token",);
//        //请求参数
        MultiValueMap<String,Object> params=new LinkedMultiValueMap<>();
        params.add("token",token);
//        //请求类型
//        //HttpEntity:spring提供一个传递http请求的实体类
//        HttpEntity entity=new HttpEntity(params,httpHeaders);
//         //通post发送请求
//        //Map.class返回类型
//        Map map = restTemplate.postForObject(url, entity,Map.class);
//        Object data = map.get("data");
        Map map = RestUtils.postWithParams(url, null, params);
        if (!map.get("code").equals("1")){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        //校验通过，给前台返回用户信息
        Object data = map.get("data");
        ObjectMapper objectMapper=new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(data);

//        PrintWriter printWriter=new PrintWriter(System.out);
//        printWriter.write(jsonString);
//   response.getWriter().write(jsonString);
        UserThreadLocal userThreadLocal=new UserThreadLocal();
        userThreadLocal.set(jsonString);


        return true;
    }
}
